package org.lld.im.service.friendship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lld.im.codec.pack.friendship.ApproverFriendRequestPack;
import com.lld.im.codec.pack.friendship.ReadAllFriendRequestPack;
import org.apache.commons.lang3.StringUtils;
import org.lld.im.common.ResponseVO;
import org.lld.im.common.constant.Constants;
import org.lld.im.common.enums.ApproverFriendRequestStatusEnum;
import org.lld.im.common.enums.FriendShipErrorCode;
import org.lld.im.common.enums.command.FriendshipEventCommand;
import org.lld.im.common.exception.ApplicationException;
import org.lld.im.service.friendship.dao.ImFriendShipRequestEntity;
import org.lld.im.service.friendship.dao.mapper.ImFriendShipRequestMapper;
import org.lld.im.service.friendship.model.req.ApproverFriendRequestReq;
import org.lld.im.service.friendship.model.req.FriendDTO;
import org.lld.im.service.friendship.model.req.ReadFriendShipRequestReq;
import org.lld.im.service.friendship.service.ImFriendShipRequestService;
import org.lld.im.service.friendship.service.ImFriendShipService;
import org.lld.im.service.seq.RedisSeq;
import org.lld.im.service.utils.MessageProducer;
import org.lld.im.service.utils.WriteUserSeq;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: LunBoWang
 * @description: 审批好友请求服务接口实现类
 * @date: 2025/3/16 下午8:11
 * @version: 1.0
 */
@Service
public class ImFriendShipRequestImpl implements ImFriendShipRequestService {
    @Resource
    private ImFriendShipRequestMapper imFriendShipRequestMapper;
    @Resource
    private ImFriendShipService imFriendShipService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    RedisSeq redisSeq;
    @Resource
    WriteUserSeq writeUserSeq;

    @Override
    public ResponseVO addFriendshipRequest(String fromId, FriendDTO dto, Integer appId) {

        QueryWrapper<ImFriendShipRequestEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", appId);
        queryWrapper.eq("from_id", fromId);
        queryWrapper.eq("to_id", dto.getToId());
        ImFriendShipRequestEntity request = imFriendShipRequestMapper.selectOne(queryWrapper);

        long seq = redisSeq.doGetSeq(appId + ":" +
                Constants.SeqConstants.FriendshipRequest);

        if (request == null) {
            request = new ImFriendShipRequestEntity();
            request.setAddSource(dto.getAddSource());
            request.setSequence(seq);
            request.setAddWording(dto.getAddWording());
            request.setAppId(appId);
            request.setFromId(fromId);
            request.setToId(dto.getToId());
            request.setReadStatus(0);
            request.setApproveStatus(0);
            request.setRemark(dto.getRemark());
            request.setCreateTime(System.currentTimeMillis());
            imFriendShipRequestMapper.insert(request);

        } else {
            //修改记录内容 和更新时间
            if (StringUtils.isNotBlank(dto.getAddSource())) {
                request.setAddWording(dto.getAddWording());
            }
            if (StringUtils.isNotBlank(dto.getRemark())) {
                request.setRemark(dto.getRemark());
            }
            if (StringUtils.isNotBlank(dto.getAddWording())) {
                request.setAddWording(dto.getAddWording());
            }
            request.setSequence(seq);
            request.setApproveStatus(0);
            request.setReadStatus(0);
            imFriendShipRequestMapper.updateById(request);
        }
        writeUserSeq.writeUserSeq(appId, dto.getToId(), Constants.SeqConstants.FriendshipRequest, seq);
        messageProducer.sendToUser(dto.getToId(), null,
                "", FriendshipEventCommand.FRIEND_REQUEST,
                request, appId);
        return ResponseVO.successResponse();
    }

    //审批好友申请
    @Override
    public ResponseVO approveFriendShip(ApproverFriendRequestReq req) {
        ImFriendShipRequestEntity imFriendShipRequestEntity = imFriendShipRequestMapper.selectById(req.getId());
        if (imFriendShipRequestEntity == null) {
            throw new ApplicationException(FriendShipErrorCode.FRIEND_REQUEST_IS_NOT_EXIST);
        }

        if (!req.getOperator().equals(imFriendShipRequestEntity.getToId())) {
            //只能处理自己的好友申请
            throw new ApplicationException(FriendShipErrorCode.NOT_APPROVER_OTHER_MAN_REQUEST);
        }

        long seq = redisSeq.doGetSeq(req.getAppId() + ":" + Constants.SeqConstants.FriendshipRequest);

        ImFriendShipRequestEntity update = new ImFriendShipRequestEntity();
        update.setApproveStatus(req.getStatus());
        update.setUpdateTime(System.currentTimeMillis());
        update.setSequence(seq);
        update.setId(req.getId());
        imFriendShipRequestMapper.updateById(update);
        writeUserSeq.writeUserSeq(req.getAppId(), req.getOperator(), Constants.SeqConstants.FriendshipRequest, seq);

        if (ApproverFriendRequestStatusEnum.AGREE.getCode() == req.getStatus()) {
            //同意好友申请
            FriendDTO dto = new FriendDTO();
            dto.setAddSource(imFriendShipRequestEntity.getAddSource());
            dto.setAddWording(imFriendShipRequestEntity.getAddWording());
            dto.setRemark(imFriendShipRequestEntity.getRemark());
            dto.setToId(imFriendShipRequestEntity.getToId());
            ResponseVO responseVO = imFriendShipService.doAddFriend(req, imFriendShipRequestEntity.getFromId(), dto, req.getAppId());
            if (responseVO.isOk() && responseVO.getCode() != FriendShipErrorCode.TO_IS_YOUR_FRIEND.getCode()) {
                //对方已经是你的好友了，无需重复添加
                return responseVO;
            }
        }
        ApproverFriendRequestPack approverFriendRequestPack = new ApproverFriendRequestPack();
        approverFriendRequestPack.setId(req.getId());
        approverFriendRequestPack.setStatus(req.getStatus());
        approverFriendRequestPack.setSequence(seq);
        messageProducer.sendToUser(imFriendShipRequestEntity.getToId(), req.getClientType(),
                req.getImei(), FriendshipEventCommand.FRIEND_REQUEST_APPROVER,
                approverFriendRequestPack, req.getAppId());
        return ResponseVO.successResponse();
    }

    //获取好友申请
    @Override
    public ResponseVO getFriendShip(String fromId, Integer appId) {
        QueryWrapper<ImFriendShipRequestEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", appId);
        queryWrapper.eq("to_id", fromId);
        List<ImFriendShipRequestEntity> requestEntityList = imFriendShipRequestMapper.selectList(queryWrapper);
        return ResponseVO.successResponse(requestEntityList);
    }

    //已读好友申请
    @Override
    public ResponseVO readFriendShipRequest(ReadFriendShipRequestReq req) {
        QueryWrapper<ImFriendShipRequestEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", req.getAppId());
        queryWrapper.eq("to_id", req.getFromId());
        long seq = redisSeq.doGetSeq(req.getAppId() + ":" + Constants.SeqConstants.FriendshipRequest);
        ImFriendShipRequestEntity imFriendShipRequestEntity = new ImFriendShipRequestEntity();
        imFriendShipRequestEntity.setReadStatus(1);
        imFriendShipRequestEntity.setSequence(seq);
        imFriendShipRequestMapper.update(imFriendShipRequestEntity, queryWrapper);
        writeUserSeq.writeUserSeq(req.getAppId(), req.getOperator(), Constants.SeqConstants.FriendshipRequest, seq);
        //TCP通知
        ReadAllFriendRequestPack readAllFriendRequestPack = new ReadAllFriendRequestPack();
        readAllFriendRequestPack.setFromId(req.getFromId());
        readAllFriendRequestPack.setSequence(seq);
        messageProducer.sendToUser(req.getFromId(), req.getClientType(),
                req.getImei(), FriendshipEventCommand.FRIEND_REQUEST_READ,
                readAllFriendRequestPack
                , req.getAppId());
        return ResponseVO.successResponse();
    }
}
